<template>
  <div>
    <crumbs @goBack="() => {}" :superiorMenu="['库存管理']" currentMenu="库存盘点" style="margin-bottom: 12px" />
    <a-card :bordered="false" style="height: calc(100vh - 175px)">
      <!-- 操作按钮区域 -->
      <div class="table-operator">
        <a-button @click="handleShowFilter" icon="filter" style="margin-right: 10px">
          筛选 <span style="color: #1890ff; margin-left: 5px">{{ searchNum }}</span></a-button
        >
        <a-button @click="showColumn" icon="unordered-list" style="margin-right: 10px"> 设置列 </a-button>
        <div class="right-btn">
          <!-- <a-button @click="exportAction(record)" style="margin-right: 20px !important">导入</a-button> -->
          <PubExport
            :exportUrl="exportUrl"
            :columns="columns"
            :propForm="getQueryParams()"
            :selectedRows="chooseArr"
            :sortForm="sortForm"
            :fullName="fullName"
            style="margin-right: 10px"
            v-if="hasButton('in:derive')"
          />
          <a-button @click="handleAdd" type="primary" class="btns" v-if="hasButton('in:add')"> +新建 </a-button>
        </div>
        <!-- <a-button @click="handleDetail" type="primary" style="float: right" icon="plus">进详情</a-button> -->
      </div>
      <!-- 设置列 -->
      <SetColumn
        columnName="设置列"
        ref="SetColumn"
        v-if="showSetColumn"
        @sureBtn="sureBtn"
        @cancelBtn="showSetColumn = false"
      />
      <!-- table区域-begin -->
      <div>
        <a-table
          v-if="tableShow"
          :key="tableKey"
          ref="table"
          size="middle"
          rowKey="id"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="false"
          :loading="loading"
          class="j-table-force-nowrap"
          :row-selection="{
            selectedRowKeys: selectedRowKeys,
            columnTitle: ' ',
            onChange: onSelectChange,
          }"
          @change="handleTableChange"
          :scroll="{ x: computedX, y: 'calc(100vh - 290px)' }"
          :components="drag(columns, 'INVENTORY_ORDER')"
        >
          <span slot="entryCode" :text="text" slot-scope="text, record">
            <a @click="handleDetail(record)">{{ text }}</a>
          </span>
          <span slot="actions" slot-scope="text, record">
            <a @click="handleEdit(record)" v-if="hasButton('in:edit')">编辑</a>
            <a-dropdown style="margin-left: 20px">
              <a class="ant-dropdown-link" v-if="hasButton('in:print') || hasButton('in:delete')">
                更多
                <a-icon type="down" />
              </a>
              <a-menu slot="overlay">
                <a-menu-item>
                  <!-- <a-button type="link" @click="printIt(record.id, true)">打印</a-button> -->
                  <printInventoryOrder v-if="hasButton('in:print')" :record="record" />
                </a-menu-item>
                <!-- <a-menu-item>
                  <a-button type="link" @click="copyIt(record)">复制</a-button>
                </a-menu-item> -->
                <a-menu-item>
                  <a-popconfirm
                    title="是否删除?"
                    ok-text="是"
                    cancel-text="否"
                    @confirm="handleDelete(record)"
                    @cancel="cancel"
                  >
                    <a style="color: #f25643; margin-left: 13px" v-if="hasButton('in:delete')">删除</a>
                  </a-popconfirm>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </span>
          <!-- title搜索条件开始 -->
          <!-- 输入框搜索 -->
          <div
            v-for="(item, i) in filterDropdownList"
            :key="i"
            style="display: flex; padding: 8px"
            :slot="item.scopedSlots.filterDropdown"
            slot-scope="{ column }"
          >
            <template>
              <a-input
                v-if="item.scopedSlots.filterDropdown === 'selectProcess'"
                @click="openIt"
                v-model="queryParam[column.searchIndex + 'Text']"
                placeholder="请选择"
                :read-only="true"
              >
                <a-icon slot="suffix" type="down" style="color: #cdcdcd; font-size: 12px" class="down-icon" />
                <a-icon
                  slot="suffix"
                  type="close-circle"
                  theme="filled"
                  class="close-icon"
                  @click="getSelectValue(false, '', [])"
                />
              </a-input>
              <j-select-user-by-dep
                v-if="item.scopedSlots.filterDropdown === 'sendPersion'"
                v-model="queryParam[`${item.searchIndex}username`]"
                :multi="item.multi"
                @changeRow="(a, b, c) => onChangeUser(b || {}, 'sendPersion')"
              ></j-select-user-by-dep>
              <j-select-user-by-dep
                v-if="item.scopedSlots.filterDropdown === 'updateBy'"
                v-model="queryParam[`${item.searchIndex}username`]"
                :multi="item.multi"
                @changeRow="(a, b, c) => onChangeUser(b || {}, 'updateBy')"
              ></j-select-user-by-dep>
              <j-select-user-by-dep
                v-if="item.scopedSlots.filterDropdown === 'createBy'"
                v-model="queryParam[`${item.searchIndex}username`]"
                :multi="item.multi"
                @changeRow="(a, b, c) => onChangeUser(b || {}, 'createBy')"
              ></j-select-user-by-dep>

              <a-input
                v-if="item.scopedSlots.filterDropdown === 'searchDropdown'"
                :placeholder="'请输入'"
                v-model="queryParam[column.searchIndex]"
                style="width: 188px"
              />
              <a-range-picker
                v-if="item.scopedSlots.filterDropdown.includes('datePicker')"
                v-model="dateForm[item.searchIndex]"
                format="YYYY-MM-DD"
                :placeholder="['开始时间', '结束时间']"
                @change="(a, b) => onOk(a, b, item.searchIndex)"
                style="width: 100%"
              />
              <a-select
                :mode="column.multi ? 'multiple' : 'default'"
                v-if="item.scopedSlots.filterDropdown === 'selectDropdown'"
                :placeholder="'请选择'"
                allowClear
                style="width: 188px"
                v-model="queryParam[`${column.searchIndex}all`]"
                @change="(a) => changeSelect(a, column.searchIndex)"
                :labelInValue="true"
              >
                <a-select-option v-for="(items, i) in column.options" :key="i" :value="items.key">{{
                  items.label
                }}</a-select-option>
              </a-select>
              <a-button
                v-if="item.scopedSlots.filterDropdown !== 'tooltip'"
                type="primary"
                style="width: 80px; margin-left: 20px"
                @click="searchQuery"
              >
                搜索
              </a-button>
            </template>
          </div>
          <a-icon slot="searchIcon" type="search" />
          <a-icon
            slot="dateIcon"
            slot-scope="filtered"
            type="filter"
            :style="{ color: filtered ? '#108ee9' : undefined }"
          />
          <span slot="none" type=""></span>
          <!-- title搜索条件结束 -->
        </a-table>
      </div>
      <!-- table区域-end -->
      <!-- 底部分页 -->
      <div class="tableFooter">
        <div style="display: inline-block; float: right">
          <a-pagination
            :total="ipagination.total"
            v-model="ipagination.current"
            :page-size-options="ipagination.pageSizeOptions"
            :page-size="ipagination.pageSize"
            @change="onChangePage"
            @showSizeChange="onChangePage"
            show-quick-jumper
            show-size-changer
          />
        </div>
      </div>
      <!-- 表格条数 -->
      <div class="tableSelect" :style="{ left: collapsed ? '253px' : '110px' }">
        <a-checkbox :indeterminate="listIndeterminate" :checked="listCheckAll" @change="onCheckAllChange"></a-checkbox>
        <span
          class="pubColor"
          @click="batchPrintAction"
          style="padding-left: 3px; color: rgb(51, 153, 255); margin-left: 8px; cursor: pointer"
          v-if="hasButton('in:delete')"
          >删除</span
        >
        <span style="margin: 0 20px">{{ `已选 ${selectedRowKeys.length}/${ipagination.total} 条` }}</span>
        <span class="pubColor" @click="clearArr" style="color: rgb(51, 153, 255); margin-left: 5px; cursor: pointer"
          >清空</span
        >
      </div>
      <!-- 侧边筛选 -->
      <a-drawer
        width="500"
        height="100vh"
        :bodyStyle="{ background: '#f5f5f5', padding: '0' }"
        :closable="true"
        :visible="showFilter"
        @close="showFilter = false"
      >
        <formSearch ref="dataSearch" @searchDate="searchDate" />
      </a-drawer>
    </a-card>
    <a-modal
      v-if="batchDeletevisible"
      :width="currentEnvironment == 'dingding' ? 1000 : 500"
      :visible="batchDeletevisible"
      :closable="false"
      :confirm-loading="false"
      @cancel="batchDeletevisible = false"
      title="批量删除"
    >
      <batch-ding-print-view v-if="currentEnvironment == 'dingding'" :ids="selectedRowKeys" />
      <div v-if="currentEnvironment != 'dingding'">是否确定批量删除！</div>
      <template slot="footer">
        <a-button key="back" @click="batchDeletevisible = false"> 取消 </a-button>
        <a-button key="submit" type="primary" @click="changeBatchDelete"> 删除 </a-button>
      </template>
    </a-modal>
    <windowForm ref="windowForm" @refresh="searchQuery"></windowForm>
    <windowDetail ref="windowDetail"></windowDetail>
    <tableSelect ref="tableSelect" @getSelectValue="getSelectValue">
      <div slot="head">
        <div class="uni-card" style="background: #fff">
          <a-form-model ref="ruleForm" layout="inline">
            <!-- <a-form-model-item label="工艺编号">
              <a-input v-model="filterFormCraft.craftCode" placeholder="请输入" />
            </a-form-model-item>
            <a-form-model-item label="工艺名称">
              <a-input v-model="filterFormCraft.craftName" placeholder="请输入" />
            </a-form-model-item>
            <a-form-model-item> -->
            <!-- <a-button @click="searchCraft()" type="primary"> 搜索 </a-button>
              <a-button style="margin-left: 10px" @click="searchResetCraft">重置</a-button>
            </a-form-model-item>-->
          </a-form-model>
        </div>
      </div>
    </tableSelect>
  </div>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { tableMixinReport } from '@/mixins/tableMixinReport'
import { columns, allColumn, processRouteColumns, getTypeList } from './column.js'
import tableDragResize from '@/mixins/tableDragResize'
import { API } from '@/api/requestFzs'
import { APILX } from '@/api/requestLx'

import { getEnableOne } from '@/api/api'
import { downFilePost } from '@/api/manage'
import tableSelect from '@/components/tableSelect'
import PubExport from '@/components/pubBtn/PubExport.vue'
import moment from 'moment'
import { mapState } from 'vuex'
import printInventoryOrder from './printInventoryOrder.vue'
import {hasButton} from '@/utils/hasPermission'

const actionArr = [
  {
    fixed: 'right',
    title: '操作',
    align: 'left',
    dataIndex: 'actions',
    width: 150,
    scopedSlots: { customRender: 'actions' },
  },
]
import tableDynamicField from '@/mixins/tableDynamicField'
export default {
  mixins: [tableMixinReport, tableDragResize, tableDynamicField],
  components: {
    windowForm: (resolve) => require(['./form'], resolve),
    windowDetail: (resolve) => require(['./detail'], resolve),
    tableSelect,
    PubExport,
    printInventoryOrder,
  },
  data() {
    return {
      // 表头
      columns: columns.map((e) => {
        e.align = 'left'
        return e
      }),
      batchDeletevisible: false,
      //全选按钮
      listIndeterminate: false,
      listCheckAll: false,
      selectedRowKeys: [],
      chooseArr: [],
      allRequestList: [],
      currentEnvironment: '',

      actionArr,
      allColumn: allColumn.map((e) => {
        e.align = 'left'
        return e
      }),
      url: {
        list: '/warehouse/warehouseEntryInfo/list',
        methods: 'post',
      },
      tableData: {},
      EntityName: this.BUSI_CONST.Entity.INVENTORY_ORDER, //用于表头设计,值保证是唯一的即可
      currentUserId: '',
      tableKey: 1.9,
      formType: 5,
      // 导出参数
      exportUrl: '/warehouse/warehouseEntryInfo/exportXls',
      fullName: `入库单 ${moment(new Date()).format('YYYY-MM-DD HH:mm')}`,
    }
  },
  computed: {
    ...mapState({
      collapsed: (state) => state.user.collapsedAno,
    }),
  },
  created() {
    // this.$store.commit('SET_CURRENT_PREFIX', '/jksaas-easyMake/easyMake')

    // getEnableOne({ id: 'WMS_WAREHOUSE_INVENTORY', type: 'add' }).then((res) => {
    //   if (res.result && res.result == 'false') {
    //     this.allColumn = this.allColumn.filter((item) => item.title != '审批状态')
    //     this.columns = this.columns.filter((item) => item.title != '审批状态')
    //   }
    // })
    let currentLogin = JSON.parse(localStorage.getItem('pro__Login_Userinfo')).value
    this.currentUserId = currentLogin.id
  },
  methods: {
    hasButton,
    // 入库单打印
    printIt() {},
    async initDictConfig() {
      getTypeList()
    },
    getSelectValue(id, text, item) {
      this.queryParam.processRouteId = id
      this.queryParam.processRouteIdText = text
      this.searchQuery()
    },
    openIt() {
      let par = {
        list: '/basicprocess/basicProcessRouteInfo/list',
        visible: true, //弹窗开启
        title: '入库单', //标题名称
        multi: false, //是否多选
        columns: processRouteColumns, //表格配置
        value: this.goodsValue, //需要回显的数据，如：id:'12323213,321312312,321312312'
        valueKey: 'id', //需要拿到数据的key，如：id，userId等
        text: this.goodsText, //回显的中文，如：'张三'
        textKey: 'processRouteName', //回显的中文key
      }
      this.$refs.tableSelect.getInit(par)
    },
    cancel() {},
    onSelectChange(selectedRowKeys, selectedRows) {
      console.log('第一个参数是；', selectedRowKeys)
      console.log('第second个参数是；', selectedRows)
      this.selectedRowKeys = selectedRowKeys
      this.chooseArr = []
      for (let tag of selectedRowKeys) {
        for (let item of this.dataSource) {
          if (tag == item.id) {
            this.chooseArr.push(item)
          }
        }
      }
      this.checkBoxStatus()
    },
    // 全选
    onCheckAllChange(e) {
      console.log('zhehsig', e.target)
      if (e.target.checked) {
        for (let item of this.dataSource) {
          this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
            return each != item.id
          })
          this.chooseArr = this.chooseArr.filter((every) => {
            return every.id != item.id
          })
          this.selectedRowKeys.push(item.id)
          this.chooseArr.push(item)
        }
      } else {
        for (let item of this.dataSource) {
          this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
            return each != item.id
          })
          this.chooseArr = this.chooseArr.filter((every) => {
            return every.id != item.id
          })
        }
      }

      this.checkBoxStatus()
    },
    onOk(a, b, key) {
      if (a.length == 0) {
        this.queryParam[`${key}Begin`] = ''
        this.queryParam[`${key}End`] = ''
        this.dateForm[key] = []
        return
      }
      this.dateForm[key] = b
      this.queryParam[`${key}Begin`] = b[0]
      this.queryParam[`${key}End`] = b[1]
    },
    clearArr() {
      this.selectedRowKeys = []
      this.chooseArr = []
      this.checkBoxStatus()
    },
    checkBoxStatus() {
      if (this.selectedRowKeys.length == 0) {
        this.listIndeterminate = false
        this.listCheckAll = false
      } else {
        let tableIds = []
        for (let item of this.dataSource) {
          tableIds.push(item.id)
        }
        let checkValue = this.isInclude(tableIds, this.selectedRowKeys)
        console.log()
        console.log('第一个参数是；', checkValue)
        if (checkValue) {
          this.listIndeterminate = false
          this.listCheckAll = true
        } else {
          this.listIndeterminate = true
          this.listCheckAll = false
        }
      }
    },
    isInclude(aa, bb) {
      return aa.every((item) => {
        return bb.some((sub) => {
          return sub === item
        })
      })
    },
    // 批量删除
    batchPrintAction() {
      this.batchDeletevisible = true
    },
    changeBatchDelete() {
      if (this.selectedRowKeys.length <= 0) {
        this.$antdMessage.error('请选择删除数据')
        return
      }
      APILX.warehouseEntryInfoDeleteBatch({ ids: this.selectedRowKeys.toString() }).then((res) => {
        this.$antdMessage.success(res.message)
        this.batchDeletevisible = false
        this.clearArr()
        this.searchQuery()
      })
    },
    changeBatchPrint() {
      this.batchDeletevisible = false
    },
    handleAdd() {
      this.$refs.windowForm.initForm()
    },
    handleEdit(v) {
      this.$refs.windowForm.initForm(v)
    },
    copyIt(v) {
      this.$refs.windowForm.initForm(v, true)
    },
    handleDetail(v) {
      this.$refs.windowDetail.initDetail(v.id)
    },
    handleDelete(v) {
      APILX.warehouseEntryInfoDelete({ id: v.id }).then((res) => {
        this.$antdMessage.success(res.message)

        this.searchQuery()
      })
    },
    exportAction(record) {
      let fileName = `库存盘点 ${record.inventoryCode}`
      let postData = {
        id: record.id,
      }
      downFilePost('/wms/wmsWarehouseInventory/exportInventoryDetails', postData).then((data) => {
        if (data.type == 'application/json') {
          const reader = new FileReader() //创建一个FileReader实例
          reader.readAsText(data, 'utf-8') //读取文件,结果用字符串形式表示
          reader.onload = function () {
            //读取完成后,**获取reader.result**
            const msg = JSON.parse(reader.result)
            this.$antdMessage.error(msg.message) //弹出错误提示
          }
          return
        }
        if (!data) {
          this.$antdMessage.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data]), fileName + '.xlsx')
        } else {
          let url = window.URL.createObjectURL(new Blob([data]))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xlsx')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
    onChangeUser(v, index, x) {
      this.$set(
        this.queryParam,
        index,
        v
          .map((e) => {
            return e.id
          })
          .toString()
      )
      this.$set(
        this.queryParam,
        `${index}realname`,
        v
          .map((e) => {
            return e.realname
          })
          .toString()
      )
      this.$set(
        this.queryParam,
        `${index}username`,
        v
          .map((e) => {
            return e.username
          })
          .toString()
      )
      setTimeout(() => {
        if (!x) {
          this.searchQuery()
          this.onChangeUser(v, index, 1)
        }
      }, 1000)
    },
    /* 撤回 */
    handleWithdraw(v) {
      let that = this
      that.$antdConfirm({
        title: '确定撤回吗？',
        content: '撤回后暂不支持再次发起',
        onOk() {
          API.operateRevoke({ flowInstId: v.flowInstId }).then((res) => {
            if (res.code == 200) {
              that.$antdMessage.success(res.message)
              that.loadData(1)
            } else {
              that.$antdMessage.error(res.message)
            }
          })
        },
        onCancel() {},
      })
    },
  },
}
</script>
<style scoped lang="less">
.right-btn {
  float: right;
  display: flex;
  justify-content: flex-end;
  button {
    margin: 0 !important;
  }
}
/deep/.ant-card-body {
  padding: 20px 16px;
}
@import '~@/assets/less/public.less';
@import '~@assets/less/common.less';
</style>
